<?php

namespace App\Controllers;
// 创建密钥
use App\Models\UserMsgModel;


class LoginController extends BaseController
{

    public function login(){
        return view('login');
    }
    public function register(){
        return view('register');
    }
    public function index(){
        return view('index');
    }
    public function welcome(){
        return view('welcome');
    }


    public function doLogin(){
        $encrypter = \Config\Services::encrypter();

       // 获取当前上下文的request
        $request = $this->request;
        $input = $request->getPost();
        // 获取数据库模型
        $userMsgModel = new UserMsgModel();
        $user = $userMsgModel->where(['username'=>$input['username'],'isDelete'=>'0'])->find();
        if($user){
            // 验证密码
            try{
                $newText = $encrypter->decrypt(base64_decode($user[0]['password']));

                if($newText == $input["password"]){
                    // 将内容存储到session
                    session()->set("user",$user[0]);
                    // 返回的依旧是字符串
                    return  json_encode(['msg'=>'登录成功','code'=>200]);
                }else{
                    return  json_encode(['msg'=>'登录失败！密码错误','code'=>403]);
                }
            }catch (\CodeIgniter\Encryption\Exceptions\EncryptionException $e){
                return  json_encode(['msg'=>'登录失败！密码错误','code'=>405]);
            }
        }else{
            // 返回的依旧是字符串
            return  json_encode(['msg'=>'登录失败！账号不存在','code'=>403]);
        }
    }

    public function doRegister(){
        $encrypter = \Config\Services::encrypter();

        // 获取当前上下文的request
        $request = $this->request;
        $input = $request->getPost();
        // 获取数据库模型
        $userMsgModel = new UserMsgModel();
        $user = $userMsgModel->where(['username'=>$input['username'],'isDelete'=>'0'])->find();
        if(!$user){
            // 如果相同用户名的用户不存在，则允许注册
            date_default_timezone_set('PRC');
            $input['registeTime'] = date('Y-m-d H:i:s',time());
            $input['isDelete'] = '0';
            unset($input['csrf_test_name']);
            // 加密密码
            $input['password'] = base64_encode($encrypter->encrypt($input['password']));

            $res = $userMsgModel->insert($input) ;
            return  json_encode(['msg'=>'注册成功','code'=>200]);
        }else{
            // 返回的依旧是字符串
            return  json_encode(['msg'=>'注册失败！用户名已经被注册','code'=>403]);
        }
    }

    public function logout(){
        // 将内容存储到session
        session()->remove("user");
        // 返回的依旧是字符串
        return  json_encode(['msg'=>'退出登录成功！即将跳转到登录页','code'=>200]);
    }

}
